<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>chat</title>
    <meta name="viewport" content="width=device-width,user-scalable=no"/>
    <style>
        .mt10 {
            margin-top: 10px;
        }
    </style>
</head>
<body>
<div>
    <button onclick="sendMsg('hello')">sendMsg('hello')</button>
</div>
<div class="mt10">
    <button onclick="sendMsg({type:'goods_price', data:'BANANA'})">查询 BANANA 价格</button>
</div>
<div class="mt10">
    <button onclick="sendMsg({type:'goods_price', data:'APPLE'})">查询 APPLE 价格</button>
</div>
<div class="mt10">
    <button onclick="sendMsg({type:'market_orders', data:{symbol:'BANANA', size:'5'}})">查询 BANANA 委托记录</button>
</div>
<script type="text/javascript">
    // const ws = new WebSocket('ws://192.168.1.134:8100/market');
    // const ws = new WebSocket('ws://localhost:8100/test');
    const ws = new WebSocket('ws://localhost:8100/ws/market');

    // 1 握手环节验证成功之后 自动触发  onopen
    ws.onopen = function() {
        console.log('握手成功')
        ws.send(JSON.stringify({type: 'connected', token: '1'}))
    }

    // 2 给服务端发送消息  send
    function sendMsg(data) {
        const typ = typeof data
        if (typ === 'object') {
            data = JSON.stringify(data)
        }
        ws.send(data)
    }

    // 3 一旦服务端有消息 自动触发  onmessage
    ws.onmessage = function(args) {
        // console.log(args)  // args是一个对象
        // 获取发送的数据
        console.log(args.data)
    }

    // 4 断开链接之后  自动触发  onclose
    ws.onclose = function() {
        ws.close()
    }
</script>
</body>
</html>
